<?php
/**
 * prepend_no_gui.php
 *
 * This file is prepended on every file and is responsible to setup
 * the environment (framework) and initialize common classes.
 * *
 * @category   babel
 * @package    BABEL
 * @author     Magnus Jonsson <magnus.jonsson@codealliance.se>
 * @author     Hannes Magnusson <hannes.magnusson@gmail.com>
 * @copyright  2008 Team babel
 * @license    LGPL
*/

include($ROOT_DIR . 'includes/babel/system_constants.php');
include($ROOT_DIR . 'includes/babel/babel_constants.php');
include($ROOT_DIR . 'includes/babel/version.php');

/**
 * Force HTTPS if required
 */
if ($_ICE_REQUIRE_SSL && $HTTP_SERVER_VARS['HTTPS'] != 'on')
{
   $newurl = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
   header("location: $newurl");
}

/**
 * Initialize Classes
 */
require('HTML/Template/PHPLIB.php');
require(_ICE_DIR.'classes/HTML.php');
require _ICE_DIR. "classes/DB.php";

$obj_tpl	= new Template_PHPLIB(_ICE_DIR.'templates/'._ICE_TEMPLATE.'/');
$obj_html	= new ICE_HTML();

/**
 * Connect to ICE Server MySQL Database
 */
try {
	$pdo = PDODB::connect();
} catch(Exception $e) {
	echo $e->getMessage();
	$e->getTrace();
	exit;
}

// FIXME: This class (classes/Log.php) needs to be rewritten
class ICE_Log {
	public function __call($func, $args) {
		/* Ignore */
	}
}

if( !isset($_SESSION['user']['username']) ) {
	if ((!isset($_GET["username"]) || !isset($_GET["token"])) && !_ICE_DEBUG) {
		header("Location: " .EXPONO_LOGIN_URI);
		exit;
	}

	if (_ICE_DEBUG) {
		if (isset($_GET['username'])) {
			$user = babel_create_bogus_user($_GET['username']);
		} elseif ($_GET["p"] != "login") {
			header("Location: /go/login");
			exit;
		}
	} else {
		$user = babel_isAuthenticated($_GET["username"], $_GET["token"]);
	}

	if (isset($user) && is_array($user)) {
		babel_login($user);
	} elseif (isset($_GET['p']) && $_GET['p'] != 'login') {
		throw new Exception("Cannot authenticate you... maybe session timed out?");
	}

	unset($_GET["username"], $_GET["token"]);

}

/**
 * LANGUAGE CONTROLLER
 */
if (!isset($_GET['lang'])) {
	$_GET['lang'] = 'en';
}
if (in_array(strtolower($_GET['lang']), $_SUPPORTED_LANGUAGES)){
	$_SESSION['params']['lang'] = strtolower($_GET['lang']);
} elseif (!isset($_SESSION['params']['lang'])) {
	$_SESSION['params']['lang'] = 'en';
}

$lang_file = 'languages'.substr($_SERVER['PHP_SELF'], 0,- 3)."lang.{$_SESSION['params']['lang']}";
if (file_exists(_ICE_DIR.$lang_file)) {
	include(_ICE_DIR.$lang_file);
}
unset($lang_file);

